package com.shangye.core;

import com.shangye.http.HttpServletRequest;
import com.shangye.http.HttpServletResponse;

import java.io.File;
import java.net.URISyntaxException;

public class DispatcherServlet {
    private static DispatcherServlet instance = new DispatcherServlet();

    public static DispatcherServlet getInstance(){
        return instance;
    }


    private static File rootDir;
    private static File staticDir;

    static {

        try {
            rootDir = new File(DispatcherServlet.class.getClassLoader().getResource(".").toURI());
            staticDir = new File(rootDir, "static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

    }
    private DispatcherServlet(){}

    public void service(HttpServletRequest request, HttpServletResponse response){
        String path = request.getUri();
        File file = new File(staticDir, path);
        if (file.exists()){
            response.setContentFile(file);
        }else {
            response.setStatusCode(404);
            response.setStatusReason("NotFound");
            file = new File(staticDir,"/root/404.html");
            response.setContentFile(file);
        }
    }
}
